#include "remotedatabase.h"

RemoteDataBase::RemoteDataBase(QObject *parent): QObject(parent), manager(new QNetworkAccessManager(this)) {
    manager = new QNetworkAccessManager(this);//connect(manager, &QNetworkAccessManager::finished, this, &RemoteDataBase::handleGetResponse);
}

bool RemoteDataBase::userRegister(QString name,QString password,int photo){
    QByteArray data = password.toUtf8();//MD5加密密码
    QByteArray hashData = QCryptographicHash::hash(data, QCryptographicHash::Md5);
    QString passwordMd5= hashData.toHex().toUpper();
    localConfig.writeLocalConfig("password",passwordMd5);
    QString ip=getLocalIPAddress();
    QUrl url("http://203.33.215.181:5000/remoteuser");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json["name"] = name;
    json["password"] = passwordMd5;
    json["ip"] = ip;
    json["photo"] = photo;
    QNetworkReply *reply = manager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, &RemoteDataBase::handlePostResponse);
    return true;
}
bool RemoteDataBase::userLogin(int id,QString password){
    QByteArray data = password.toUtf8();//MD5加密密码
    QByteArray hashData = QCryptographicHash::hash(data, QCryptographicHash::Md5);
    QString passwordMd5= hashData.toHex().toUpper();
    QUrl url("http://203.33.215.181:5000/remotelogin");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json["id"] = id;
    json["password"] = passwordMd5;
    QNetworkReply *reply = manager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, &RemoteDataBase::handleGetResponse);
    return true;
}
bool RemoteDataBase::userLoginAuto(int id,QString password){
    QUrl url("http://203.33.215.181:5000/remotelogin");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json["id"] = id;
    json["password"] = password;
    QNetworkReply *reply = manager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, &RemoteDataBase::handleGetResponse);
    return true;
}
bool RemoteDataBase::sendChatMessage(int id,int idFrom,QString chatMessage){
    QUrl url("http://203.33.215.181:5000/chat");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json["id"] = id;
    json["idfrom"] = idFrom;
    json["chatmessage"] = chatMessage;
    QNetworkReply *reply = manager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, &RemoteDataBase::handlePostExperience);
    return true;
}
bool RemoteDataBase::saveExperience(int id,int experience,int level,int immortalclass){
    QUrl url("http://203.33.215.181:5000/saveexperience");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json["id"] = id;
    json["experience"] = experience;
    json["level"] = level;
    json["immortalclass"] = immortalclass;
    QNetworkReply *reply = manager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, &RemoteDataBase::handlePostExperience);
    return true;
}
bool RemoteDataBase::saveLinggen(int id,int linggen){
    QUrl url("http://203.33.215.181:5000/savelinggen");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json["id"] = id;
    json["linggen"] = linggen;
    QNetworkReply *reply = manager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, &RemoteDataBase::handlePostExperience);
    return true;
}

void RemoteDataBase::handleGetResponse() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString message;
    QJsonDocument doc;
    if (reply && reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        doc = QJsonDocument::fromJson(data);
        if (doc.isObject()) {
            QJsonObject obj = doc.object();
            if (obj.contains("message")) {
                message = obj["message"].toString();
            }
        }
    } else {
        qDebug() << "Error:" << reply->errorString();
    }
    emit userReceived(message, doc.array()); // 发送 QVariantList
    reply->deleteLater();
}

void RemoteDataBase::handlePostResponse() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    bool success = false;
    double message;
    if (reply && reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if (doc.isObject()) {
            QJsonObject obj = doc.object();
            if (obj.contains("id")) {
                success = true;
                message = obj["id"].toDouble();
            }
        }
    } else {
        qDebug() << "Error:" << reply->errorString();
    }
    emit userAdded(success,message); // 假设有一个信号userAdded
    reply->deleteLater();
}
void RemoteDataBase::handlePostExperience() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QJsonDocument doc;
    if (reply && reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        doc = QJsonDocument::fromJson(data);
        if (doc.isObject()) {
            QJsonObject obj = doc.object();
            if (obj.contains("message")) {
                reply->deleteLater();
                return;
            }
        }
    } else {
        qDebug() << "Error:" << reply->errorString();
    }
    emit chatMessageReceived(doc.array()); // 发送 QVariantList
    reply->deleteLater();
}

QString RemoteDataBase::getLocalIPAddress() const {
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list) {
        // 我们只关心IPv4地址且排除回环地址
        if(address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost))
            return address.toString();
    }
    return "No local IP found";
}
void RemoteDataBase::sendRequest(const QString &inputText) {
    QNetworkRequest request;
    //request.setUrl(QUrl("https://api.deepseek.com/v1/search"));
    request.setUrl(QUrl("https://api.deepseek.com/chat/completions"));
    request.setRawHeader("Authorization", ("Bearer " + apiKey).toUtf8());
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject data;
    data["model"] = "deepseek-v1";
    QJsonArray messages;
    QJsonObject message;
    message["role"] = "user";
    message["content"] = inputText;
    messages.append(message);
    data["messages"] = messages;

    QJsonDocument doc(data);
    QByteArray postData = doc.toJson();

    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        RemoteDataBase::handleResponse(reply);
    });
}
void RemoteDataBase::handleResponse(QNetworkReply *reply) {
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseData = reply->readAll();
        QJsonObject jsonResponse = QJsonDocument::fromJson(responseData).object();
        QJsonArray choices = jsonResponse["choices"].toArray();
        if (!choices.isEmpty()) {
            QJsonObject choice = choices[0].toObject();
            QString responseText = choice["message"].toObject()["content"].toString();
            emit responseReceived(responseText);
        }
    } else {
        qDebug() << "Error:" << reply->errorString();
    }
    reply->deleteLater();
}

/*bool RemoteDataBase::writeStickyNote(int snOwner,QString snContent,int64_t timeWrite,int64_t timeWarn){  //写入便签纸
    return true;
}

QVariantList RemoteDataBase::readDataSN(int userId){//读取用户便签数
    QVariantList result;
    return result;
}

bool RemoteDataBase::delStickyNote(int userId,int snIndex){//删除用户便签
    return true;
}*/
